import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
import Redis from 'ioredis';

@Injectable()
export class RedisService implements OnModuleDestroy {
  constructor(@Inject('REDIS_CLIENT') private readonly redis: Redis) {}

  async get(key: string): Promise<string | null> {
    return this.redis.get(key);
  }

  async set(key: string, value: string, ttlSeconds?: number): Promise<'OK'> {
    if (ttlSeconds) {
      return this.redis.set(key, value, 'EX', ttlSeconds);
    }
    return this.redis.set(key, value);
  }

  async del(key: string): Promise<number> {
    return this.redis.del(key);
  }

  async publish(channel: string, message: string): Promise<number> {
    return this.redis.publish(channel, message);
  }

  async subscribe(channel: string, callback: (msg: string) => void) {
    const sub = new Redis(this.redis.options); // 新连接用于订阅
    await sub.subscribe(channel);
    sub.on('message', (_, message) => {
      callback(message);
    });
  }

  async info() {
    return await this.redis.info('server');
  }

  onModuleDestroy() {
    this.redis.disconnect();
  }
}
